package app.modules.account.business.service;

import app.framework.config.FrontGlobalConfig;
import app.framework.security.captcha.CaptchaCacheUtil;
import app.modules.account.dto.web.WebCaptchaDTO;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.springframework.stereotype.Service;

/**
 * @author mh.z
 */
@Service
public class LoginService {
    private FrontGlobalConfig frontConfig;

    private static int CAPTCHA_WIDTH = 134;
    private static int CAPTCHA_HEIGHT = 44;
    private static int CAPTCHA_CODE_COUNT = 4;
    private static int CAPTCHA_LINE_COUNT = 150;

    public LoginService(FrontGlobalConfig frontConfig) {
        this.frontConfig = frontConfig;
    }

    /**
     * 获取验证码
     *
     * @return
     */
    public WebCaptchaDTO getCaptcha() {
        WebCaptchaDTO captchaDTO = new WebCaptchaDTO();

        boolean captchaEnabled = Boolean.TRUE.equals(frontConfig.getCaptchaEnabled());
        captchaDTO.setCaptchaEnabled(captchaEnabled);

        if (captchaEnabled) {
            LineCaptcha captcha = CaptchaUtil.createLineCaptcha(CAPTCHA_WIDTH, CAPTCHA_HEIGHT,
                    CAPTCHA_CODE_COUNT, CAPTCHA_LINE_COUNT);
            String captchaCode = captcha.getCode();
            // 保存验证码到缓存中，用于后续请求进行验证码的匹配
            String captchaKey = CaptchaCacheUtil.save(captchaCode);

            String imageBase64 = captcha.getImageBase64();
            String captchaData = "data:image/png;base64," + imageBase64;

            captchaDTO.setCaptchaKey(captchaKey);
            captchaDTO.setCaptchaCode(captchaCode);
            captchaDTO.setCaptchaData(captchaData);
        }

        return captchaDTO;
    }

}
